"""
对话数据模式
"""

from typing import Optional, List, Dict, Any
from datetime import datetime
from pydantic import BaseModel


class ConversationBase(BaseModel):
    """对话基础模式"""
    title: Optional[str] = None
    model_config_id: Optional[int] = None
    knowledge_base_id: Optional[int] = None
    prompt_template_id: Optional[int] = None


class ConversationCreate(ConversationBase):
    """创建对话模式"""
    pass


class ConversationUpdate(BaseModel):
    """更新对话模式"""
    title: Optional[str] = None
    model_config_id: Optional[int] = None
    knowledge_base_id: Optional[int] = None
    prompt_template_id: Optional[int] = None


class UpdateTitleRequest(BaseModel):
    """更新标题请求模式"""
    title: str


class ConversationResponse(ConversationBase):
    """对话响应模式"""
    id: int
    user_id: int
    is_active: bool
    message_count: int
    created_at: datetime
    updated_at: datetime
    last_message_at: Optional[datetime] = None
    
    class Config:
        from_attributes = True
    
    @classmethod
    def model_validate(cls, obj, **kwargs):
        """自定义验证方法，将 updated_at 映射为 last_message_at"""
        if hasattr(obj, '__dict__'):
            # 如果是 ORM 对象
            data = {
                "id": obj.id,
                "user_id": obj.user_id,
                "title": obj.title,
                "model_config_id": obj.model_config_id,
                "knowledge_base_id": obj.knowledge_base_id,
                "prompt_template_id": obj.prompt_template_id,
                "is_active": obj.is_active,
                "message_count": obj.message_count,
                "created_at": obj.created_at,
                "updated_at": obj.updated_at,
                "last_message_at": obj.updated_at  # 使用 updated_at 作为最后消息时间
            }
            return cls(**data)
        else:
            # 如果是字典，调用父类方法
            return super().model_validate(obj, **kwargs)


class MessageBase(BaseModel):
    """消息基础模式"""
    role: str
    content: str
    metadata: Optional[Dict[str, Any]] = None
    token_count: Optional[int] = None


class MessageCreate(MessageBase):
    """创建消息模式"""
    conversation_id: int


class MessageResponse(MessageBase):
    """消息响应模式"""
    id: int
    conversation_id: int
    created_at: datetime
    
    class Config:
        from_attributes = True


class ConversationWithMessages(ConversationResponse):
    """包含消息的对话响应模式"""
    messages: List[MessageResponse] = []


class ConversationSummary(BaseModel):
    """对话摘要模式"""
    id: int
    title: str
    message_count: int
    created_at: datetime
    updated_at: datetime
    last_message_at: Optional[datetime] = None
    model_name: Optional[str] = None
    knowledge_base_name: Optional[str] = None
    prompt_template_name: Optional[str] = None
    recent_messages: List[Dict[str, Any]] = []
